{% extends 'inventory/base.html' %}

{% block title %}会员管理 - {{ block.super }}{% endblock %}

{% block content %}
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                    <div>
                        <h2 class="card-title mb-0">会员管理</h2>
                        <p class="text-muted mb-md-0">管理所有会员信息</p>
                    </div>
                    <div class="d-flex flex-wrap gap-2">
                        <a href="{% url 'member_level_list' %}" class="btn btn-outline-primary">
                            <i class="bi bi-award me-1"></i> 会员等级管理
                        </a>
                        <a href="{% url 'member_purchases' %}" class="btn btn-outline-info">
                            <i class="bi bi-search me-1"></i> 会员消费查询
                        </a>
                        <a href="{% url 'member_create' %}" class="btn btn-primary">
                            <i class="bi bi-person-plus me-1"></i> 添加会员
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="row g-3 mb-4 align-items-center">
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text bg-light"><i class="bi bi-search"></i></span>
                            <input type="text" class="form-control" id="searchInput" placeholder="搜索会员名或手机号...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="dropdown">
                            <button class="btn btn-outline-primary dropdown-toggle" type="button" id="levelFilterDropdown" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                                <i class="bi bi-filter me-1"></i> 会员等级筛选
                            </button>
                            <div class="dropdown-menu p-3" style="width: 250px;" aria-labelledby="levelFilterDropdown">
                                <div class="mb-2">
                                    <div class="form-check">
                                        <input class="form-check-input level-filter-all" type="checkbox" id="level-all" checked>
                                        <label class="form-check-label" for="level-all">
                                            全部等级
                                        </label>
                                    </div>
                                </div>
                                <div class="mb-2">
                                    <hr class="dropdown-divider">
                                </div>
                                <div style="max-height: 200px; overflow-y: auto;">
                                    {% for level in member_levels %}
                                    <div class="form-check">
                                        <input class="form-check-input level-filter-item" type="checkbox" id="level-{{ level.id }}" value="{{ level.id }}">
                                        <label class="form-check-label" for="level-{{ level.id }}">
                                            {{ level.name }}
                                        </label>
                                    </div>
                                    {% endfor %}
                                </div>
                                <div class="mt-3 d-flex justify-content-between">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="clearLevelFilters">清除</button>
                                    <button type="button" class="btn btn-sm btn-primary" id="applyLevelFilters">应用筛选</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="dropdown">
                            <button class="btn btn-outline-info dropdown-toggle" type="button" id="rechargedFilterDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="bi bi-wallet me-1"></i> 充值会员
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="rechargedFilterDropdown">
                                <li><a class="dropdown-item recharge-filter active" href="#" data-recharged="all">全部会员</a></li>
                                <li><a class="dropdown-item recharge-filter" href="#" data-recharged="yes">充值会员</a></li>
                                <li><a class="dropdown-item recharge-filter" href="#" data-recharged="no">非充值会员</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="d-flex justify-content-md-end">
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="bi bi-sort-down me-1"></i> 
                                    排序: {{ sort_label }}
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li><a class="dropdown-item {% if sort_by == 'name' %}active{% endif %}" href="?sort=name">按姓名</a></li>
                                    <li><a class="dropdown-item {% if sort_by == 'total_spend' %}active{% endif %}" href="?sort=total_spend">按累计消费</a></li>
                                    <li><a class="dropdown-item {% if sort_by == 'purchase_count' %}active{% endif %}" href="?sort=purchase_count">按消费次数</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>会员信息</th>
                                <th>会员等级</th>
                                <th>积分</th>
                                <th>账户余额</th>
                                <th>累计消费</th>
                                <th>消费次数</th>
                                <th>注册日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for member in members %}
                            <tr data-level="{{ member.level.id }}" data-recharged="{{ member.is_recharged|yesno:'yes,no' }}">
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0 me-3">
                                            <div class="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 48px; height: 48px; font-weight: 500;">
                                                {{ member.name|slice:"0:1"|default:"-" }}
                                            </div>
                                        </div>
                                        <div>
                                            <h6 class="mb-0">{{ member.name }}
                                                {% if member.is_recharged %}
                                                <span class="badge bg-success ms-1"><i class="bi bi-wallet2"></i> 充值会员</span>
                                                {% endif %}
                                            </h6>
                                            <small class="text-muted">{{ member.phone }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge bg-info text-dark">{{ member.level.name }}</span>
                                </td>
                                <td>
                                    <span class="fw-bold">{{ member.points }}</span>
                                </td>
                                <td>
                                    <span class="fw-bold text-success">¥{{ member.balance }}</span>
                                </td>
                                <td>
                                    <span class="fw-bold text-success">¥{{ member.total_spend }}</span>
                                </td>
                                <td>
                                    <span class="badge bg-secondary">{{ member.purchase_count }} 次</span>
                                </td>
                                <td>
                                    <small>{{ member.created_at|date:"Y-m-d" }}</small>
                                </td>
                                <td>
                                    <div class="btn-group">
                                        <a href="{% url 'member_details' member.id %}" class="btn btn-sm btn-outline-info" title="查看详情">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="{% url 'member_edit' member.id %}" class="btn btn-sm btn-outline-primary" title="编辑">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <a href="{% url 'member_recharge' member.id %}" class="btn btn-sm btn-outline-success" title="充值">
                                            <i class="bi bi-cash-coin"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="6" class="text-center py-5">
                                    <div class="d-flex flex-column align-items-center">
                                        <i class="bi bi-people text-muted" style="font-size: 2.5rem;"></i>
                                        <p class="mt-3 mb-1">暂无会员数据</p>
                                        <small class="text-muted">点击"添加会员"按钮创建会员</small>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                
                <!-- 分页控件 -->
                {% if members %}
                <div class="d-flex justify-content-between align-items-center mt-4">
                    <div class="text-muted small">
                        显示 1 至 {{ members|length }} 条，共 {{ members|length }} 条记录
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item disabled">
                                <a class="page-link" href="#" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <li class="page-item active"><a class="page-link" href="#">1</a></li>
                            <li class="page-item disabled">
                                <a class="page-link" href="#" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('input', filterMembers);
        
        // 等级筛选功能
        const levelAllCheckbox = document.querySelector('.level-filter-all');
        const levelCheckboxes = document.querySelectorAll('.level-filter-item');
        const applyFiltersBtn = document.getElementById('applyLevelFilters');
        const clearFiltersBtn = document.getElementById('clearLevelFilters');
        
        // 当前选中的等级ID数组
        let selectedLevels = [];
        
        // 当前的充值会员筛选状态
        let rechargedFilter = 'all';
        
        // 初始化禁用等级选项
        levelCheckboxes.forEach(checkbox => {
            checkbox.disabled = true;
        });
        
        // 全选/取消全选
        levelAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            levelCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
                checkbox.disabled = isChecked;
            });
            
            if (isChecked) {
                selectedLevels = [];
            }
        });
        
        // 单个等级勾选
        levelCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                // 如果勾选了任何等级，取消"全部"选项
                if (this.checked) {
                    levelAllCheckbox.checked = false;
                    
                    // 检查是否已添加
                    if (!selectedLevels.includes(this.value)) {
                        selectedLevels.push(this.value);
                    }
                } else {
                    // 移除取消勾选的等级
                    const index = selectedLevels.indexOf(this.value);
                    if (index > -1) {
                        selectedLevels.splice(index, 1);
                    }
                    
                    // 如果没有选中任何等级，勾选"全部"
                    if (document.querySelectorAll('.level-filter-item:checked').length === 0) {
                        levelAllCheckbox.checked = true;
                        levelCheckboxes.forEach(cb => {
                            cb.disabled = true;
                        });
                    }
                }
            });
        });
        
        // 清除筛选
        clearFiltersBtn.addEventListener('click', function() {
            levelAllCheckbox.checked = true;
            levelCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
                checkbox.disabled = true;
            });
            selectedLevels = [];
            filterMembers();
            
            // 更新筛选下拉按钮文本
            document.getElementById('levelFilterDropdown').innerHTML = '<i class="bi bi-filter me-1"></i> 会员等级筛选';
        });
        
        // 应用筛选
        applyFiltersBtn.addEventListener('click', function() {
            const dropdown = document.getElementById('levelFilterDropdown');
            
            if (levelAllCheckbox.checked) {
                dropdown.innerHTML = '<i class="bi bi-filter me-1"></i> 会员等级筛选';
            } else {
                const selectedCount = document.querySelectorAll('.level-filter-item:checked').length;
                dropdown.innerHTML = `<i class="bi bi-filter me-1"></i> 已选 ${selectedCount} 个等级`;
            }
            
            filterMembers();
            
            // 关闭下拉菜单
            const dropdownMenu = document.querySelector('.dropdown-menu');
            const bsDropdown = bootstrap.Dropdown.getInstance(dropdown);
            if (bsDropdown) {
                bsDropdown.hide();
            }
        });
        
        // 充值会员筛选功能
        const rechargeFilterLinks = document.querySelectorAll('.recharge-filter');
        rechargeFilterLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                
                // 移除所有链接的active类
                rechargeFilterLinks.forEach(l => l.classList.remove('active'));
                // 给当前点击的链接添加active类
                this.classList.add('active');
                
                // 设置当前筛选状态
                rechargedFilter = this.dataset.recharged;
                
                // 更新下拉按钮文本
                const btnText = this.textContent.trim();
                document.getElementById('rechargedFilterDropdown').innerHTML = `<i class="bi bi-wallet me-1"></i> ${btnText}`;
                
                // 应用筛选
                filterMembers();
            });
        });
        
        function filterMembers() {
            const searchTerm = searchInput.value.toLowerCase();
            const rows = document.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                // 忽略空行
                if (!row.querySelector('td:first-child')) return;
                
                const memberName = row.querySelector('h6')?.textContent.toLowerCase() || '';
                const memberPhone = row.querySelector('small')?.textContent.toLowerCase() || '';
                const rowLevel = row.dataset.level;
                const rowRecharged = row.dataset.recharged;
                
                // 检查搜索条件
                const matchesSearch = memberName.includes(searchTerm) || memberPhone.includes(searchTerm);
                
                // 检查等级条件
                let matchesLevel = true;
                if (!levelAllCheckbox.checked && selectedLevels.length > 0) {
                    matchesLevel = selectedLevels.includes(rowLevel) || selectedLevels.includes(String(rowLevel));
                }
                
                // 检查充值会员条件
                let matchesRecharged = true;
                if (rechargedFilter !== 'all') {
                    matchesRecharged = rowRecharged === rechargedFilter;
                }
                
                // 同时满足搜索、等级和充值条件才显示
                if (matchesSearch && matchesLevel && matchesRecharged) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
    });
</script>
{% endblock %}